package app.beit.finportal.controller;

import java.io.File;
import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import app.beit.finportal.bean.DocumentsBean;
import app.beit.finportal.bean.MSConfigBean;
import app.beit.finportal.service.DocumentsService;
import app.beit.finportal.service.MSConfigService;
import app.beit.finportal.utils.MimeTypeUtils;
import app.beit.finportal.utils.constr.SessionConstr;

@Controller
@RequestMapping("/download")
public class DownloadController extends BaseController {

	@Autowired
	private DocumentsService documentsService;
	@Autowired
	private MimeTypeUtils mimeTypeUtils;
	@Autowired
	private MSConfigService msConfigService;

	@RequestMapping
	public String index(final HttpServletRequest request) throws Exception {
		super.startProcess(request);
		//super.removeAllSession(request);
		request.setAttribute(SessionConstr.ACTIVE_PAGE, "download");

		try {
			final List<DocumentsBean> beans = this.documentsService.getAll();
			if (beans != null && beans.size() > 0) {
				request.setAttribute(SessionConstr.DOCUMENTS_ALL_DATAS, beans);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return "download";
	}

	@RequestMapping(value = "/getFile/{fileName:.+}", method = RequestMethod.GET)
	public void getFile(final @PathVariable("fileName") String fileName, HttpServletResponse response) {
		try {
			
			int indexOfPeriod = fileName.indexOf(".");
			String mimeType = fileName.substring(indexOfPeriod+1);
			response.setContentType(mimeTypeUtils.getContentType(mimeType));
			
			// get your file as InputStream
			MSConfigBean bean = this.msConfigService.getFileLocation();
			final String saveDirectoryPath = bean.getValue();//this.messageSource.getMessage("file.upload.location", null, new Locale("EN"));
			File initialFile = new File(saveDirectoryPath + fileName);
			InputStream is = FileUtils.openInputStream(initialFile);
			// copy it to response's OutputStream
			org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
			response.flushBuffer();
			response.getOutputStream();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}
}
